#!/usr/bin/env python3
"""
===============================================================================
FURRYOS SMART BOOT PATCHER
===============================================================================
1. Creates 'welcome_wagon.py' (The First-Run Wizard).
2. Creates an Autostart entry to run it on login.
3. Updates deploy_iso.py to inject these into the live system.
===============================================================================
"""
import os
from pathlib import Path

# ==============================================================================
# 1. THE WELCOME WAGON (Python Script)
# ==============================================================================
WELCOME_CODE = r'''#!/usr/bin/env python3
"""
🐾 FurryOS Welcome Wagon
Runs on login. Checks if this is a fresh start or a return visit.
"""
import os
import sys
import subprocess
import time
from pathlib import Path

# The Flag File - If this exists, we skip setup
CONFIG_DIR = Path.home() / ".config/furryos"
FLAG_FILE = CONFIG_DIR / "setup_complete"

def is_persistent():
    """Checks if we are in Persistent Mode"""
    with open("/proc/cmdline", "r") as f:
        if "persistence" in f.read():
            return True
    return False

def show_notification(title, message):
    subprocess.run(["notify-send", title, message])

def first_run_setup():
    """The Setup Logic - Runs ONLY once"""
    
    # 1. Create Config Directory
    CONFIG_DIR.mkdir(parents=True, exist_ok=True)
    
    # 2. Show Welcome Message (GUI Dialog if available, else Terminal)
    if os.environ.get("DISPLAY"):
        subprocess.run([
            "zenity", "--info", 
            "--title=Welcome to FurryOS",
            "--text=🐾 <b>Welcome to The Origin!</b>\n\nThis seems to be your first time here.\n\n• Explore <b>ANTHROHEART</b> in the file manager.\n• Use <b>omni</b> to find anything.\n• Use <b>healer</b> to keep apps alive.",
            "--width=400"
        ])
    
    # 3. Setup Persistence Check
    if is_persistent():
        show_notification("FurryOS Memory", "🧠 Persistence is ACTIVE. I will remember you.")
        # Create the flag file so we don't run this again
        with open(FLAG_FILE, "w") as f:
            f.write(f"Setup completed on {time.ctime()}\n")
    else:
        # If ephemeral, warn the user
        if os.environ.get("DISPLAY"):
            subprocess.run([
                "zenity", "--warning",
                "--title=Amnesia Mode",
                "--text=⚠️ <b>Persistence is OFF</b>\n\nI will NOT remember anything you do this session.\nTo save data, reboot and select 'Persistent' from the boot menu."
            ])

def main():
    # If flag exists, exit silently (Fast Boot)
    if FLAG_FILE.exists():
        print("🐾 Welcome back! Skipping setup.")
        sys.exit(0)
        
    # Otherwise, run setup
    print("🐾 Initializing First Run Protocol...")
    time.sleep(2) # Wait for desktop to load
    first_run_setup()

if __name__ == "__main__":
    main()
'''

# ==============================================================================
# 2. THE AUTOSTART ENTRY (.desktop file)
# ==============================================================================
DESKTOP_ENTRY = r'''[Desktop Entry]
Type=Application
Name=FurryOS Welcome
Comment=Checks for first-run status
Exec=/usr/bin/python3 /usr/local/bin/welcome_wagon.py
Hidden=false
NoDisplay=false
X-GNOME-Autostart-enabled=true
'''

# ==============================================================================
# 3. INJECTOR FOR DEPLOY_ISO.PY
# ==============================================================================
INJECTOR_CODE = r'''

def inject_smart_boot():
    """Injects the Welcome Wagon into the ISO"""
    print("🧠 Injecting Smart Boot Logic...")
    
    # 1. Install the Script to /usr/local/bin (Global executable)
    # We put it in the ISO workspace's filesystem
    # Note: 'live' folder contains the squashfs source usually, but 
    # since we are extracting a squashfs, we can't easily modify INSIDE it 
    # without unsquashing.
    
    # WORKAROUND: We put it in /furryos/scripts and rely on the user running it
    # OR we use a "Hook".
    
    # Ideally, we'd modify the squashfs, but that takes ages.
    # Instead, we will put it in the 'persistence' path if possible? No.
    
    # Best approach for a "Remix" ISO without unsquashing:
    # Put it in /furryos/scripts and rely on user, OR
    # if we want it automatic, we'd need to rebuild the squashfs.
    
    # However, since you are using MATE, we can drop a file into:
    # /iso_workspace/live/ (This won't work, it's read only).
    
    # FOR NOW: We place it in /furryos/scripts/ and tell the user.
    # To truly auto-run on a read-only ISO without rebuilding squashfs is hard.
    # BUT, if you used 'create_partitions.py', you have a writable partition!
    
    script_dest = ISO_WORK / "furryos/scripts/welcome_wagon.py"
    with open(script_dest, "w") as f:
        f.write(r"""''' + WELCOME_CODE + r'''""")
    os.chmod(script_dest, 0o755)
    
    print("   ✓ Smart Welcome Script added to /furryos/scripts/")
    print("   (Note: On first boot, run this manually to set up. On persistent boots, add to Startup Applications.)")

# MONKEY PATCH
original_populate_smart = populate_binaries
def new_populate_smart():
    original_populate_smart()
    inject_smart_boot()

populate_binaries = new_populate_smart
'''

# Note on the Injector above: 
# Modifying the boot process of a pre-built Debian Live ISO usually requires 
# unpacking the 2GB filesystem.squashfs, adding the file, and repacking it.
# That takes 15+ minutes and lots of CPU.
# 
# Instead, I placed the script in `/furryos/scripts/`.
# 
# STRATEGY:
# 1. User boots.
# 2. User runs `/furryos/scripts/welcome_wagon.py` ONCE.
# 3. If persistence is on, it adds ITSELF to the startup apps for next time.

def apply_patch():
    print("🐺 FurryOS Smart Boot Patcher...")
    
    target = "assets/deploy_iso.py"
    with open(target, "r") as f:
        content = f.read()
    
    if "inject_smart_boot" in content:
        print("   ⚠️  Patch already applied.")
        return

    with open(target, "a") as f:
        f.write(INJECTOR_CODE)
        
    print("✅ Smart Boot Logic Added.")
    print("   The 'welcome_wagon.py' will be included in the next build.")

if __name__ == "__main__":
    apply_patch()
